package net.lab1024.smartadmin.module.weapp.login;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpMaJsCode2SessionResult;
import net.lab1024.smartadmin.common.constant.ResponseCodeConst;
import net.lab1024.smartadmin.common.domain.ResponseDTO;
import net.lab1024.smartadmin.common.weixin.WxCpConfiguration;
import net.lab1024.smartadmin.common.weixin.WxMaConfiguration;
import net.lab1024.smartadmin.common.weixin.utils.JsonUtils;
import net.lab1024.smartadmin.constant.CommonConst;
import net.lab1024.smartadmin.module.system.employee.EmployeeDao;
import net.lab1024.smartadmin.module.system.employee.domain.dto.CpUserDTO;
import net.lab1024.smartadmin.module.system.employee.domain.dto.EmployeeDTO;
import net.lab1024.smartadmin.module.system.employee.domain.entity.EmployeeEntity;
import net.lab1024.smartadmin.module.system.login.LoginTokenService;
import net.lab1024.smartadmin.module.system.login.domain.LoginDetailVO;
import net.lab1024.smartadmin.module.system.login.domain.RequestTokenBO;
import net.lab1024.smartadmin.module.system.privilege.service.PrivilegeEmployeeService;
import net.lab1024.smartadmin.module.system.role.basic.domain.dto.RoleBatchDTO;
import net.lab1024.smartadmin.module.system.role.roleemployee.RoleEmployeeService;
import net.lab1024.smartadmin.module.system.systemconfig.SystemConfigService;
import net.lab1024.smartadmin.module.system.systemconfig.constant.SystemConfigEnum;
import net.lab1024.smartadmin.module.weapp.login.domain.Authorize;
import net.lab1024.smartadmin.module.weapp.login.domain.LoginInfoVO;
import net.lab1024.smartadmin.module.weapp.login.domain.WeappLoginDTO;
import net.lab1024.smartadmin.module.weapp.users.dao.UsersDao;
import net.lab1024.smartadmin.module.weapp.users.domain.dto.UsersAddDTO;
import net.lab1024.smartadmin.module.weapp.users.domain.entity.UsersEntity;
import net.lab1024.smartadmin.module.weapp.users.domain.vo.UsersVO;
import net.lab1024.smartadmin.util.SmartBeanUtil;
import net.lab1024.smartadmin.util.SmartDigestUtil;
import net.lab1024.smartadmin.util.SmartRequestTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.management.relation.Role;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.Date;


/**
 * [  ]
 *
 * @author wuqian
 * @version 1.0
 * @company 1024lab.net
 * @copyright (c) 2018 1024lab.netInc. All rights reserved.
 * @date 2021/3/09 0027 下午 18:10
 * @since JDK1.8
 */
@Slf4j
@Service
public class WeappLoginService {

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private UsersDao usersDao;

    @Autowired
    private RoleEmployeeService roleEmployeeService;

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private WeappLoginTokenService weappLoginTokenService;
    @Autowired
    private PrivilegeEmployeeService privilegeEmployeeService;


    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 登陆
     *
     * @param loginForm 登录名 密码
     * @return 登录用户基本信息 openid/ session_key
     */
    public ResponseDTO<LoginInfoVO> login(@Valid WeappLoginDTO loginForm, HttpServletRequest request) {

        RequestTokenBO requestToken = SmartRequestTokenUtil.getRequestUser();
        String code = loginForm.getCode();
        WxMaJscode2SessionResult session = null;
        WxCpMaJsCode2SessionResult sessionqy = null;
        LoginInfoVO logininfoDTO = new LoginInfoVO();
        UsersVO usersVO = new UsersVO();
        if(loginForm.getEnv() != null && loginForm.getEnv().equalsIgnoreCase("wxwork")){
            //企业微信环境
            Integer agentid = Integer.valueOf(systemConfigService.getCacheByKey(SystemConfigEnum.Key.CP_AGENTID).getConfigValue());
            final WxCpService wxService = WxCpConfiguration.getCpService(agentid);
            try {
                sessionqy = wxService.jsCode2Session(code);
                sessionqy.getCorpId();
                sessionqy.getUserId();
                logininfoDTO.setOpenid(sessionqy.getUserId());
                logininfoDTO.setSessionKey(sessionqy.getSessionKey());
                CpUserDTO cpUserDTO = employeeDao.getCpUserByUserId(sessionqy.getUserId());
                if(cpUserDTO == null){
                    return ResponseDTO.wrapMsg(ResponseCodeConst.ERROR_PARAM,"没有找到对应的员工");
                }

                usersVO.setUid(cpUserDTO.getId());


            }catch (WxErrorException e) {
                this.logger.error(e.getMessage(), e);
                return ResponseDTO.wrapMsg(ResponseCodeConst.ERROR_PARAM,"微信授权失败");
            }
        }else {
            String appid = systemConfigService.getCacheByKey(SystemConfigEnum.Key.WEAPP_APPID).getConfigValue();
            //多小程序切换
            final WxMaService wxService = WxMaConfiguration.getMaService(appid);
            try {
                session = wxService.getUserService().getSessionInfo(code);
            } catch (WxErrorException e) {
                this.logger.error(e.getMessage(), e);
                return ResponseDTO.wrapMsg(ResponseCodeConst.ERROR_PARAM, "微信授权失败");
            }


            this.logger.info(session.getSessionKey());
            this.logger.info(session.getOpenid());
            logininfoDTO.setOpenid(session.getOpenid());
            logininfoDTO.setSessionKey(session.getSessionKey());
            //TODO 可以增加自己的逻辑，关联业务相关数据
//            JsonUtils.toJson(session);
            usersVO = usersDao.selectByOpenid(session.getOpenid());
            if (usersVO == null) {
                //创建员工帐号
                EmployeeEntity employeeEntity = new EmployeeEntity();
                employeeEntity.setActualName("");
                employeeEntity.setDepartmentId(99999L);
                employeeEntity.setLoginName(session.getOpenid());
                employeeEntity.setCreateUser((long) 0);
                employeeEntity.setLoginPwd(SmartDigestUtil.encryptPassword(CommonConst.Password.SALT_FORMAT, "123456"));
                employeeDao.insertAndGetId(employeeEntity);

                //绑定微信帐号
                UsersAddDTO usersAddDTO = new UsersAddDTO();
                usersAddDTO.setOpenid(session.getOpenid());
                usersAddDTO.setUid(employeeEntity.getId());
                usersAddDTO.setCreateTime(new Date());
                usersAddDTO.setUpdateTime(new Date());
                UsersEntity usersEntity = SmartBeanUtil.copy(usersAddDTO, UsersEntity.class);
                usersDao.insert(usersEntity);

                RoleBatchDTO roleBatchDTO = new RoleBatchDTO();
                roleBatchDTO.setEmployeeIds(Arrays.asList(employeeEntity.getId()));
                roleBatchDTO.setRoleId(Long.valueOf(40)); //添加默认角色
                roleEmployeeService.batchAddEmployeeRole(roleBatchDTO);
                usersVO = SmartBeanUtil.copy(usersAddDTO, UsersVO.class);
            }


        }
        String token = weappLoginTokenService.generateToken(usersVO);
        Boolean superman = privilegeEmployeeService.isSuperman(usersVO.getUid());
        logininfoDTO.setAuthorize(new Authorize(token, (new Date().getTime()) / 1000, superman));
        return ResponseDTO.succData(logininfoDTO);

    }
}
